import { Users } from "@/api/model/userSearchTypes";
import { reqSearchUsers } from "@/api/userSearch";
import { RootState } from "@/app/store";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

// 状态类型
interface UserSearchState {
  firstView: boolean;
	loading: boolean;
	errorMsg: string;
	users: Users
}

// 初始状态
const initialState: UserSearchState = {
  firstView: true,
	loading: false,
	errorMsg: '',
	users: []
}

// 搜索的异步action
export const search = createAsyncThunk(
  'userSearch/search',
  (searchName: string) => reqSearchUsers(searchName)
)


// 当前redux模块的管理对象slice
const userSearchSlice = createSlice({
  name: 'userSearch', // 标识名称
  initialState, // 初始状态
  // 配置同步action对应的reducer
  reducers: {},
  // 配置异步action对应的reducer
  extraReducers: (builder) => {
    builder
      .addCase(search.pending, (state) => { // 请求开始前的reducer
        state.firstView = false
        state.loading = true
        state.users = []
        state.errorMsg = ''
      })
      .addCase(search.fulfilled, (state, action) => { // 请求成功后的reducer
        state.loading = false
        state.users = action.payload.items
      })
      .addCase(search.rejected, (state, action) => { // 请求失败后的reducer
        state.loading = false
        state.errorMsg = action.error.message as string
      })
  }
})

// 默认暴露reducer
export default userSearchSlice.reducer

// 暴露读取state数据的select函数
export const selectUserSearch = (state: RootState) => state.userSearch